import { createStore } from 'vuex'
import products from '../products'

// 从 localStorage 获取购物车数据
const savedCart = localStorage.getItem('cart')
const initialCart = savedCart ? JSON.parse(savedCart) : []

export default createStore({
  state: {
    products: products,
    cart: initialCart
  },
  getters: {
    cartItemCount: (state) => {
      return state.cart.reduce((total, item) => total + item.quantity, 0)
    }
  },
  mutations: {
    addToCart(state, product) {
      const existingItem = state.cart.find(item => item.id === product.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        state.cart.push({
          ...product,
          quantity: 1
        })
      }
      // 保存到 localStorage
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    removeFromCart(state, productId) {
      const index = state.cart.findIndex(item => item.id === productId)
      if (index > -1) {
        state.cart.splice(index, 1)
        // 保存到 localStorage
        localStorage.setItem('cart', JSON.stringify(state.cart))
      }
    },
    updateQuantity(state, { productId, quantity }) {
      const item = state.cart.find(item => item.id === productId)
      if (item) {
        item.quantity = quantity
        // 保存到 localStorage
        localStorage.setItem('cart', JSON.stringify(state.cart))
      }
    },
    clearCart(state) {
      state.cart = []
      // 清除 localStorage 中的购物车数据
      localStorage.removeItem('cart')
    }
  },
  actions: {
    addToCart({ commit }, product) {
      commit('addToCart', product)
    },
    removeFromCart({ commit }, productId) {
      commit('removeFromCart', productId)
    },
    updateQuantity({ commit }, payload) {
      commit('updateQuantity', payload)
    },
    clearCart({ commit }) {
      commit('clearCart')
    }
  }
})
